<?php
/*
 *	Created on 12.04.2008 / 12:59:14
 *	@filename run.php 
 *	User: tomusdrw (tomusdrw.blacksoft.eu)
 *	@author: Blacksoft.eu (c) 2008, 2009
 *	@package: tempaq2 
 *	
 */

require_once('bot/conf.php');

function debug($msg, $type=DBG_ERROR, $dbglvl=1) {
	$premsg = date('[H:i.s d M] ').'('.$dbglvl.') ';
	switch($type) {
		case DBG_ERROR:
			$premsg .= 'ERROR: ';
			break;
		case DBG_INFO:
			$premsg .= 'INFO: ';
			break;
		case DBG_WARN:
			$premsg .= 'WARN: '; 
			break;
		default:
			$premsg .= 'DEBUG: ';
	}
	$msg = $premsg.$msg."\n";
	if (is_callable('bot_base::set_debug')) {
		$debug = bot_base::set_debug();
	} else $debug = BOT_DEBUG;
	
	if ($debug>=$dbglvl) {
		echo $msg;
		flush();
	} 
	if (DBG_LOG && $dbglvl<3) {
		if (@$f = fopen(BOT_LOG, 'a')) {
			fwrite($f, $msg);
			fclose($f);
		} else {
			debug('Couldn\'t open log file!', DBG_ERROR, 1);
		}
	}
}

if (file_exists(BOT_LOCK_FILE)&&((time()-(int)file_get_contents(BOT_LOCK_FILE))<100)) die(BOTNAME." is already running.\n");

require_once(BOT_PATH.'bot.php');
require_once(SMARTIRC);
require_once(BOT_PATH.'lang.php');
require_once(BOT_PATH.'handle_errors.php');
require_once(BOT_PATH.'module.php');

error_reporting(E_ALL);
date_default_timezone_set('Europe/Warsaw');
debug('Running '.BOTNAME.'['.BOTVER.'] by blacksoft.eu', DBG_INFO);
if (!is_executable(PHP_PATH)) die('Fatal Error: Check php executable path!'."\n"); 
$irc = &new Net_SmartIRC();
$bot = &new bot($irc, (isset($_SERVER['argv']) && isset($_SERVER['argv'][1]) && $_SERVER['argv'][1] == '--safe'));


$irc->setDebug(SMARTIRC_DEBUG_NONE);
$irc->setUseSockets(TRUE);
$irc->setChannelSyncing(TRUE);
$irc->setAutoReconnect(true);
//$irc->setAutoRetry(true);
$irc->setCtcpVersion(BOTNAME."v. ".BOTVER);

$irc->registerTimehandler(2000, $bot, 'ontimer');
$irc->registerActionhandler(SMARTIRC_TYPE_JOIN, ALL, $bot, 'onjoin');
$irc->registerActionhandler(SMARTIRC_TYPE_PART, ALL, $bot, 'onleave');
$irc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, ALL, $bot, 'onchannelmessage');
$irc->registerActionhandler(SMARTIRC_TYPE_QUERY, ALL, $bot, 'onquery');
$irc->registerActionhandler(SMARTIRC_TYPE_TOPICCHANGE, ALL, $bot, 'ontopic');
$irc->registerActionhandler(SMARTIRC_TYPE_NICKCHANGE, ALL, $bot, 'onnick');
$irc->registerActionhandler(SMARTIRC_TYPE_ALL, ALL, $bot,  'onall');

//tworzymy lock file
if (file_put_contents(BOT_LOCK_FILE, $a=time(), LOCK_EX)) {
	debug('Lock file created (with value: '.$a.')', DBG_INFO, 3);
} else {
	debug('Couldn\'t create lock file!', DBG_ERROR, 1);
}
$bot->runningsince = $a;

if ($irc->connect(SERVER, PORT)) {
	$irc->login(BOTNAME, BOTNAME." v.".BOTVER, 8, BOTNAME);
	$irc->join(array(CHANNEL));
	$irc->listen();
	$irc->disconnect();
} else {
	debug("Connection ERROR", DBG_ERROR, 0);
}
if (file_exists(BOT_LOCK_FILE))
	unlink(BOT_LOCK_FILE);
debug(BOTNAME.' terminated.', DBG_INFO);
?>